﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WordRacer.Domain.Model.Dictionaries
{
  public class TrieGameDictionary : IGameDictionary
  {
    private Tries.Trie<string> _trie;
    private int _wordCount;

    public TrieGameDictionary()
    {
      _trie = new Tries.Trie<string>();
      _wordCount = 0;
    }

    public void AddWord(string newWord)
    {
      var aNewWord = newWord.ToUpper();
      _trie.Put(aNewWord, aNewWord);
      _wordCount += 1;
    }

    public void AddWordList(IList<string> wordsToAdd)
    {
      foreach (var newWord in wordsToAdd)
      {
        this.AddWord(newWord);
      }
    }

    public bool Contains(string wordToLookup)
    {
      _trie.Matcher.ResetMatch();//start over
      foreach (char letter in wordToLookup.ToCharArray())
	    {
        if (!_trie.Matcher.NextMatch(letter))
        {
          return false; 
        }
	    }
      return _trie.Matcher.IsExactMatch();
    }

    public int WordCount
    {
      get 
      {
        return _wordCount;
      }
    }

    public bool possibleFutureWord(string currentWord)
    {
      _trie.Matcher.ResetMatch();
      foreach (char letter in currentWord.ToCharArray())
      {
        if (!_trie.Matcher.NextMatch(letter))
        {
          return false;
        }
      }
      var possibleWords = _trie.Matcher.GetPrefixMatches();
      if (_trie.Matcher.IsExactMatch()) //need to remove this exact match from the results
      {
        possibleWords.Remove(currentWord);
      }
      return possibleWords.Count > 0;
    }
  }
}
